<template>
  <div class="lc-cesium">
    <div class="lc-cesium_map" id="cesium-3d-viewer"></div>
    <div v-if="loading" class="loading-indicator">地图加载中...</div>
    <div v-if="error" class="error-message">地图加载失败: {{ error }}</div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import {
  Viewer,
  Cartesian3,
  Color,
  SceneMode,
  WebMapTileServiceImageryProvider,
} from "cesium";
import * as Cesium from 'cesium'
import "cesium/Build/Cesium/Widgets/widgets.css";
import normalIcon from '../assets/image/normal.png'
import clickIcon from '../assets/image/mark2.png'
import labelIcon from '../assets/image/mark2-rect.png'

const clientId = import.meta.env.VITE_JYSLAPI_CLIENT_ID;

const loading = ref(true);
const error = ref<string | null>(null);

// 全局变量
let viewer: Viewer | null = null;

// 龙华区坐标（深圳市中心）
const LONGHUA_POSITION = Cartesian3.fromDegrees(114.155799, 22.617691, 90000);

/**
 * 创建信息Canvas元素
 * @param info 信息对象
 * @param valueKey 值键名
 * @param changeType 变化类型
 * @returns 包含canvas和清理方法的对象
 */
 const createInfoCanvas = (info: any, valueKey?: string, changeType?: string) => {
    // 创建canvas元素
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    if (!ctx) return { canvas, cleanup: () => {} };

    // 设置canvas尺寸（根据内容动态调整）
    const padding = 10;
    const lineHeight = 20;
    let width = 50; // 默认宽度
    let height = 75; // 初始高度只有padding

    // 计算文本宽度
    const text = info?.[valueKey ?? 'label'] || '';
    ctx.font = valueKey ? '16px Arial' : '14px Arial';
    const textWidth = ctx.measureText(text).width;
    width = Math.max(width, textWidth + padding * 2);
    height += lineHeight;

    // 设置canvas尺寸
    canvas.width = width;
    canvas.height = height;
    
    // 绘制背景
    const bgImageUrl = changeType 
        ? clickIcon 
        : info?.[valueKey ? 'icon' : 'labelIcon'] ?? (valueKey ? normalIcon : labelIcon);
    
    if (bgImageUrl) {
        // 如果有背景图片，先加载图片
        const image = new Image();
        image.crossOrigin = 'Anonymous';
        image.onload = () => {
            // 重新获取context（防止内存泄漏）
            const reloadCtx = canvas.getContext('2d');
            if (!reloadCtx) return;
            
            // 绘制背景图片
            reloadCtx.drawImage(image, 0, 0, canvas.width, canvas.height);
            
            // 绘制文本
            reloadCtx.font = valueKey ? '16px Arial' : '14px Arial';
            reloadCtx.fillStyle = valueKey ? '#333' : '#666';
            reloadCtx.textBaseline = 'top';
            reloadCtx.fillText(
                text, 
                padding, 
                padding
            );
        };
        image.src = bgImageUrl;
    } else {
        // 没有背景图片，绘制纯色背景
        ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // 绘制边框
        ctx.strokeStyle = '#ddd';
        ctx.lineWidth = 1;
        ctx.strokeRect(0.5, 0.5, canvas.width - 1, canvas.height - 1);
        
        // 绘制文本
        ctx.font = valueKey ? '16px Arial' : '14px Arial';
        ctx.fillStyle = valueKey ? '#333' : '#666';
        ctx.textBaseline = 'top';
        ctx.fillText(
            text, 
            padding, 
            padding
        );
    }

    // 清理方法
    const cleanup = () => {
        // 这里可以添加任何需要的清理逻辑
    };

    return { canvas, cleanup };
};

// 初始化3D视图
function initViewer(): void {
  try {
    viewer = new Viewer("cesium-3d-viewer", {
      timeline: false,
      animation: false,
      geocoder: false,
      homeButton: false,
      sceneModePicker: false,
      baseLayerPicker: false,
      navigationHelpButton: false,
      fullscreenButton: false,
      imageryProvider: false,
      skyBox: false,
      skyAtmosphere: false,
      sceneMode: SceneMode.SCENE3D,
      scene3DOnly: true,
      orderIndependentTranslucency: false,
      selectionIndicator: false, //poiont默认点击框
    });

    // 移除默认底图
    viewer.imageryLayers.remove(viewer.imageryLayers.get(0));

    // 优化性能设置
    viewer.scene.debugShowFramesPerSecond = false;
    // viewer.scene.screenSpaceCameraController.inertia = 0.9;
    viewer.scene.screenSpaceCameraController.enableTranslate = true;
    viewer.scene.screenSpaceCameraController.minimumZoomDistance = 1000;
    viewer.scene.globe.baseColor = Color.TRANSPARENT;

    //poiont双击事件取消
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
      Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
    );


    const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);

    handler.setInputAction(function (click: any): void {
      // 检查点击是否发生在点上
      var pickedObject = viewer?.scene.pick(click.position);
      if (Cesium.defined(pickedObject)) {
        console.log(pickedObject);
        // 在这里添加你的点击处理代码
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK); // 或者使用 RIGHT_CLICK, MOUSE_MOVE 等事件类型


    // 设置初始视角
    viewer.camera.setView({ destination: LONGHUA_POSITION });

  } catch (err) {
    error.value = `初始化Viewer失败: ${err instanceof Error ? err.message : String(err)}`;
    loading.value = false;
  }
}

// 加载瓦片地图服务
async function addTileLayer(): Promise<void> {
  if (!viewer) return;

  try {
    const access_token = '0c50ee0ba3b84b388dc1cdbeecc0657c';

    const url = `jysl/service/api/e99b765798d1412b9c2b458a1473396e/igs/rest/services/SZMAP/SZDZDT_2024_Yingji_T1_4490/WMTSServer?client_id=${clientId}&access_token=${access_token}`;

    const tkUrl = 'http://t3.tianditu.gov.cn/vec_w/wmts?tk=666e7c17a9350414b1e66d099d07e654'

    const tkTextUrl = 'http://t0.tianditu.gov.cn/cia_c/wmts?tk=666e7c17a9350414b1e66d099d07e654'

    // 自定义瓦片服务

    const provider = new WebMapTileServiceImageryProvider({
      url: tkUrl,
      // layer: "SZMAP:SZDZDT_2024_Yingji_T1_4490",
      layer: "vec",
      style: "default",
      format: "image/png",
      tileMatrixSetID: "w",
      maximumLevel: 20,  // 提高层级
      tilingScheme: new Cesium.WebMercatorTilingScheme(),  // 强制 WebMercator
    });

    // const provider = await Zondy.WebMapTileServiceImageryProvider.fromUrl(url);
    // const tkVoider = await Zondy.WebMapTileServiceImageryProvider.fromUrl(tkUrl);
    // const tkText = await Zondy.WebMapTileServiceImageryProvider.fromUrl(tkTextUrl);
    if (viewer) {
      // 添加图层
      // viewer.imageryLayers.addImageryProvider(tkVoider);
      // // viewer.imageryLayers.addImageryProvider(tkText);
      viewer.imageryLayers.addImageryProvider(provider);
    }

  } catch (err) {
    console.log(err)
    error.value = `加载瓦片地图服务失败: ${err instanceof Error ? err.message : String(err)}`;
    loading.value = false;
  }
}

function addMarker() {
  if (!viewer) return;

  viewer.entities.removeAll();

  const value = {
    value: '机',
    label: '深圳宝安国际机场',
    icon: normalIcon
  }

  const valueInfo = createInfoCanvas(value, 'value');
  document.getElementById('cesium-3d-viewer')?.appendChild(valueInfo.canvas);

  viewer.entities.add({
    position: Cartesian3.fromDegrees(113.808156, 22.636116),
    name: '深圳宝安国际机场',
    code: 4444,
    id: 77777,
    // point: {
    //   pixelSize: 10,
    //   color: Color.YELLOW,
    //   outlineColor: Color.BLACK,
    //   outlineWidth: 2,
    //   heightReference: HeightReference.CLAMP_TO_GROUND,
    //   disableDepthTestDistance: 99000000,
    // },
    billboard: {
      image: valueInfo.canvas,
      // width: 100,
      // height: 100,
      disableDepthTestDistance: 99000000,
    },
  });
}

// 初始化地图
async function initMap(): Promise<void> {
  try {
    initViewer();
    await addTileLayer();
    addMarker();
    loading.value = false;
  } catch (err) {
    error.value = `地图初始化失败: ${err instanceof Error ? err.message : String(err)}`;
    loading.value = false;
    console.error("Map initialization failed:", err);
  }
}

onMounted(() => {
  initMap();
});

onBeforeUnmount(() => {
  if (viewer && !viewer.isDestroyed()) {
    viewer.destroy();
    viewer = null;
  }
});
</script>

<style lang="scss" scoped>
.lc-cesium {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  padding: 20px;
  width: 100%;
  height: 100%;
  box-sizing: border-box;

  &_map {
    position: relative;
    width: 100%;
    height: 100%;

    :deep(.cesium-widget) {
      canvas {
        image-rendering: optimizeSpeed;
        image-rendering: -moz-crisp-edges;
        image-rendering: -webkit-optimize-contrast;
        image-rendering: optimize-contrast;
        image-rendering: pixelated;
        -ms-interpolation-mode: nearest-neighbor;
      }
    }
  }

  .loading-indicator,
  .error-message {
    position: absolute;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    padding: 10px 20px;
    width: 50%;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    border-radius: 4px;
    z-index: 999;
    text-align: center;
  }

  .error-message {
    background: rgba(255, 0, 0, 0.7);
  }
}

:deep(.value-font) {
    width: 50px;
    height: 70px;
    font-size: 20px;
    color: white;
    font-weight: 600;
    display: grid;
    place-content: center;

    p {
        transform: translate(0, -18%);
    }
}

:deep(.label-font) {
    width: 190px;
    height: 41px;
    font-size: 14px;
    color: white;
    font-weight: 600;
    letter-spacing: 1px;
    display: flex;
    align-items: center;

    p {
        padding-left: 26px;

    }
  }
</style>